package com.lck.blogmanager.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lck.blogmanager.common.Response;
import com.lck.blogmanager.req.*;
import com.lck.blogmanager.res.FileDetailRes;
import com.lck.blogmanager.res.FilePageRes;
import com.lck.blogmanager.res.UserFileDetailRes;
import com.lck.blogmanager.res.UserPageFileRes;
import com.lck.blogmanager.service.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.lck.blogmanager.Enum.CommonConstant.WINDOWS_FILE_PATH;

/**
 * 文件
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/4/7 18:30
 */

@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
@RestController
public class FileController {

    private final FileService fileService;


    /**
     * 用户浏览文件列表
     *
     * @param req
     * @return
     */
    @PostMapping("/userPageFile")
    public Response<Page<UserPageFileRes>> userPageFile(@RequestBody UserPageFileReq req) {
        Page<UserPageFileRes> info = fileService.userPageFile(req);
        return Response.success(info);
    }

    /**
     * 用户获取文件详情
     *
     * @param fileId
     * @return
     */
    @GetMapping("/userFileDetail/{fileId}")
    public Response<UserFileDetailRes> userFileDetail(@PathVariable Integer fileId) {
        UserFileDetailRes res = fileService.userFileDetail(fileId);
        return Response.success(res);
    }

    /**
     * 文件下载
     * @param path
     * @param response
     */
    @GetMapping("/download")
    public void download(String path, HttpServletResponse response) {
        try {
            String preStr = WINDOWS_FILE_PATH;
            // path是指想要下载的文件的路径
            File file = new File(preStr+path);
            log.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            log.info("文件后缀名：" + ext);
            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
            fileService.downloadCount(path);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 管理员文件列表
     *
     * @param req
     * @return
     */
    @PostMapping("/page")
    public Response<Page<FilePageRes>> pageFile(@RequestBody FilePageReq req) {
        Page<FilePageRes> info = fileService.pageFile(req);
        return Response.success(info);
    }


    /**
     * 管理员文件详情
     * @param fileId
     * @return
     */
    @GetMapping("/detail/{fileId}")
    public Response<FileDetailRes> detail(@PathVariable Integer fileId) {
        FileDetailRes res = fileService.detail(fileId);
        return Response.success(res);
    }

    /**
     * 管理员审核文件
     * @param req
     * @return
     */
    @PostMapping("/audit")
    public Response auditFile(@RequestBody AuditFileReq req){
        fileService.auditFile(req);
        return Response.success();
    }

    /**
     * 点赞
     * @return
     */
    @GetMapping("/like")
    public Response likeFile(Integer fileId){
        fileService.likeFile(fileId);
        return Response.success();
    }

    /**
     * 收藏
     * @return
     */
    @PostMapping("/collect")
    public Response collectFile(Integer fileId){
        fileService.collectFile(fileId);
        return Response.success();
    }


}
